import store from "@/store";
import router from "@/router";
import "nprogress/nprogress.css"; // progress bar style
import NProgress from "nprogress"; // progress bar
import getPageTitle from "@/utils/get-page-title";
import { getToken } from "@/utils/auth"; // get token from cookie

NProgress.configure({ showSpinner: false }); // NProgress Configuration

// no redirect whitelist
const whiteList = [
    "/login",
];

router.beforeEach(async (to, from, next) => {
    // start progress bar
    NProgress.start();

    // set page title
    document.title = getPageTitle(to.meta.title);

    // determine whether the user has logged in
    const hasToken = getToken();

    if (!hasToken) {
        /* has no token */

        if (whiteList.includes(to.path)) {
            // in the free login whitelist, go directly
            next();
        } else {
            // other pages that do not have permission to access are redirected to the login page.
            next(`/login?redirect=${to.path}`);
            NProgress.done();
        }
    } else if (to.path === "/login") {
        // if is logged in, redirect to the home page
        next({ path: "/" });
        // if home to home
        NProgress.done();
    } else if (!store.getters.userInfo || !store.getters.userInfo.roles) {
        try {
            // get user info
            const userInfo = await store.dispatch("user/userInfoAction");
            const accessRoutes = await store.dispatch("permission/generateRoutes", userInfo.roles);
            router.addRoutes(accessRoutes);
            next({ ...to, replace: true });
        } catch (error) {
            // eslint-disable-next-line no-console
            console.error(error);
            // remove token and go to login page to re-login
            store.dispatch("user/logout");
            next(`/login?redirect=${to.path}`);
            // if login to login
            NProgress.done();
        }
    } else {
        next();
    }
});

router.afterEach(() => {
    // finish progress bar
    NProgress.done();
});
